package com.boost.tjvm.reference;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

public class TestWeakReference {


    private static int _1M = 1024 * 1024;

    private static final ReferenceQueue<Object> queue = new ReferenceQueue<>();

    public static void main(String[] args) {

        Thread thread = new Thread(() -> {
            int cnt = 0;
            WeakReference<byte[]> k;

            while (true){
                while ((k = (WeakReference) queue.poll()) != null) {
                    System.out.println((cnt++) + "回收了:" + k);

                    System.out.println(k.get().length);

                }
                try {
                    Thread.sleep(1111l);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.setDaemon(true);
        thread.start();

        Object value = new Object();
        Map<Object, Object> map = new HashMap<>();
        for (int i = 0; i < 10000; i++) {
            byte[] bytes = new byte[_1M];
            WeakReference<byte[]> weakReference = new WeakReference<byte[]>(bytes, queue);
            map.put(weakReference, value);
        }
        System.out.println("map.size->" + map.size());


    }

}
